package com.crm.service;

import com.crm.entity.Lost;
import com.crm.repository.LostRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service("lostService")
public class LostServiceImpl implements LostService {
    @Resource
    LostRepository lostRepository;

    @Override
    public List<Lost> findAllLost() {
        return lostRepository.findAll();
    }

    @Override
    public Lost saveLost(Lost lost) {
        return lostRepository.save(lost);
    }

    @Override
    public void deleteLostById(Integer ChanceId) {
        lostRepository.deleteById(ChanceId);
    }

    @Override
    public void deleteLost(Lost lost) {
        lostRepository.delete(lost);
    }

    @Override
    public Lost getLost(Integer LostId) {
        return lostRepository.findById(LostId).get();
    }

    @Override
    public Page<Lost> findLost(String lstCustName, String lstCustManagerName, Pageable pageable) {
        Specification<Lost> specification = new Specification<Lost>() {
            @Override
            public Predicate toPredicate(Root<Lost> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (lstCustName != null && !lstCustName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("lstCustName"), "%" + lstCustName + "%"));
                }
                if (lstCustManagerName != null && !lstCustManagerName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("lstCustManagerName"), "%" + lstCustManagerName + "%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return lostRepository.findAll(specification, pageable);
    }
}
